const path = require('path');
const webpack = require('webpack');
const glob = require('glob-all');
const config = require('./prod.conf');
const merge = require('webpack-merge');
const utils = require('../component/utils');
const baseWebpackConfig = require('./webpack.base.conf');
const _ = require('lodash');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin');
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;

module.exports = function ({subProjectName}) {
    const htmlFiles = glob.sync(`src/${subProjectName}/pages/*/*.html`, {
        cwd: path.resolve(__dirname, '..'),
    });
    const htmlPlugins = _.map(htmlFiles, function (filename) {
        const basename = path.basename(filename, '.html');
        const pluginConfig = {
            template: filename,
            filename: `${config.assetsRoot}/${subProjectName}/${basename}.html`,
            // 页面模板需要加对应的js脚本，如果不加这行则每个页面都会引入所有的js脚本
            chunks: ['manifest', 'vendor', basename],
            inject: true,
            minify: {
                removeComments: true,
                collapseWhitespace: true,
                removeAttributeQuotes: true
            },
            chunksSortMode: 'dependency'
        };
        return new HtmlWebpackPlugin(pluginConfig);
    });

    const manifestFiles = glob.sync(`src/${subProjectName}/pages/*/manifests/**/*.json`, {
        cwd: path.resolve(__dirname, '..'),
    });

    const manifestPlugins = _.map(manifestFiles, function (filename) {
        const pluginConfig = {
            context: path.resolve(__dirname, '..'),
            manifest: require(path.resolve(__dirname, '..', filename)),
        };
        return new webpack.DllReferencePlugin(pluginConfig);
    });

    // copy custom static assets
    const copyPlugins = [];
    if (glob.sync(path.resolve(__dirname, '../static', subProjectName)).length) {
        copyPlugins.push(new CopyWebpackPlugin([
            {
                from: path.resolve(__dirname, '../static', subProjectName),
                to: './',
                ignore: ['.*']
            }
        ]));
    }

    return merge(baseWebpackConfig(config, {subProjectName}), {
        output: {
            path: path.resolve(config.assetsRoot, subProjectName),
            publicPath: `/${subProjectName}/`,
            filename: utils.assetsPath('js/[name].[chunkhash].js', config.assetsSubDirectory),
        },
        module: {
            rules: utils.styleLoaders({
                sourceMap: true,
                extract: true
            })
        },
        devtool: false,
        plugins: [
            // http://vuejs.github.io/vue-loader/en/workflow/production.html
            new webpack.DefinePlugin({
                'process.env': JSON.stringify(process.env.NODE_ENV)
            }),
            new webpack.optimize.UglifyJsPlugin({
                compress: {
                    warnings: false
                },
                sourceMap: true
            }),
            // extract css into its own file
            new ExtractTextPlugin({
                filename: utils.assetsPath('css/[name].[contenthash].css', config.assetsSubDirectory)
            }),
            // Compress extracted CSS. We are using this plugin so that possible
            // duplicated CSS from different components can be deduped.
            new OptimizeCSSPlugin(),
            // generate dist index.html with correct asset hash for caching.
            // you can customize output by editing /index.html
            // see https://github.com/ampedandwired/html-webpack-plugin
            // split vendor js into its own file
        ].concat(manifestPlugins).concat(htmlPlugins).concat([
            new webpack.optimize.CommonsChunkPlugin({
                name: 'vendor',
                minChunks: function (module, count) {
                    // any required modules inside node_modules are extracted to vendor
                    return (
                        module.resource &&
                        /\.js$/.test(module.resource) &&
                        module.resource.indexOf(
                            path.join(__dirname, '../node_modules')
                        ) === 0
                    )
                }
            }),
            // extract webpack runtime and module manifest to its own file in order to
            // prevent vendor hash from being updated whenever app bundle is updated
            new webpack.optimize.CommonsChunkPlugin({
                name: 'manifest',
                chunks: ['vendor']
            }),
        ]).concat(copyPlugins).concat([
            new BundleAnalyzerPlugin(),
        ])
    });
};
